const router = require('koa-router')()

let chapterList = [
  {
    chapterId: 1,
    chapterTitle: "民生人社｜2023年河北省毕业生就业市场3月2...",
    timer: "2023-03-03"
  },
  {
    chapterId: 2,
    chapterTitle: "最新公示！河北首批义务教育学校课后服务示范拟入...",
    timer: "2023-03-03"
  },
  {
    chapterId: 3,
    chapterTitle: "河北2家单位上榜！工信部公布新名单",
    timer: "2023-03-03"
  }
]

router.get('/', async (ctx, next) => {
  await ctx.render('index', {
    title: 'Hello Koa 2!'
  })
})

router.get("/getdata", async (ctx, next) => {
  ctx.body = "recieved data";
})

router.get("/getlist", async (ctx, next) => {
  ctx.body = chapterList;
})

router.post("/del", async (ctx, next) => {
  let id = ctx.request.body.id;
  let index = '';
  for (let i = 0; i < chapterList.length; i++) {
    if (chapterList[i]["chapterId"] == id) {
      index = i;
    }
  }
  chapterList.splice(index, 1);
  ctx.body = "success";
})

router.post("/sub", async (ctx, next) => {
  let chapter = {
    chapterId: Math.random(),
    chapterTitle: ctx.request.body.chapterTitle,
    timer: ctx.request.body.timer
  }
  chapterList.push(chapter);
  ctx.body = "ok";
})
router.post("/changelist", async (ctx, next) => {
  let id = ctx.request.body.id
  let index = ''
  for (let i = 0; i < chapterList.length; i++) {
    if (chapterList[i]["chapterId"] == id) {
      index = i
    }
  }
  let chapter = {
    chapterId: id,
    chapterTitle: ctx.request.body.chapterTitle,
    timer: chapterList[index].timer
  }
  chapterList[index] = chapter
  console.log(chapterList)
  return ctx.body = "ok"

})
router.post("/subform", async (ctx, next) => {
  let body = ctx.request.body
  let dateObj = new Date(body.timer)
  let timer = dateObj.getFullYear() + "-" + (dateObj.getMonth() + 1) + "-" + dateObj.getDate()
  let chapterObj = {
    chapterId: chapterList.length + 1,
    chapterTitle: body.chapterTitle,
    timer: timer,
  }
  chapterList.push(chapterObj)
  return ctx.body = "ok"
})

router.get('/string', async (ctx, next) => {
  ctx.body = 'koa2 string'
})

router.get('/json', async (ctx, next) => {
  ctx.body = {
    title: 'koa2 json'
  }
})

module.exports = router